package com.soboot.common.config.job.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.soboot.base.util.StringUtil;
import com.soboot.common.config.job.XxlJobGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author:
 * @createTime: 2023年01月28日 21:16:47
 * @version:
 * @Description: 执行器service
 * @Copyright:
 */
@Lazy
@Service
public class JobGroupService {

    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;

    @Value("${xxl.job.executor.appname}")
    private String cAppName;

    @Value("${xxl.job.executor.title}")
    private String cTitle;

    @Autowired
    private JobLoginService jobLoginService;

    /**
     * 获取调度中心执行器列表(模糊查询)
     * @param appName 实例名
     * @param title 执行器名
     * @return
     */
    public List<XxlJobGroup> getJobGroup(String appName,String title) {

        String url = adminAddresses+"/jobgroup/pageList";

        Map<String,Object> formMap = new HashMap<>(16);
        if(StringUtil.isNotBlank(appName)){
            formMap.put("appname",appName);
        }else{
            formMap.put("appname",cAppName);
        }
        if(StringUtil.isNotBlank(title)){
            formMap.put("title",title);
        }else{
            formMap.put("title",cTitle);
        }

        HttpResponse response = HttpRequest.post(url)
                .form(formMap)
                .cookie(jobLoginService.getCookie())
                .execute();

        String body = response.body();
        JSONArray array = JSONObject.parseObject(body).getJSONArray("data");
        List<XxlJobGroup> list = array.toJavaList(XxlJobGroup.class);
        return list;
    }

    /**
     * 判断执行器是否已经在调度中心注册过
     * @param appName
     * @param title
     * @return
     */
    public boolean checkGroup(String appName,String title){

        List<XxlJobGroup> jobGroup = getJobGroup(appName,title);
        Optional<XxlJobGroup> optional = jobGroup.stream()
                .filter(xxlJobGroup -> xxlJobGroup.getAppname().equals(appName==null?cAppName:appName)
                        && xxlJobGroup.getTitle().equals(title==null?cTitle:title))
                .findAny();
        return optional.isPresent();
    }

    /**
     * 自动注册执行器
     * @param appName
     * @param title
     * @return
     */
    public boolean registerGroup(String appName,String title){

        String url = adminAddresses+"/jobgroup/save";

        if(StringUtil.isBlank(appName)){
            appName = cAppName;
            title = cTitle;
        }
        HttpResponse response = HttpRequest.post(url)
                .form("appname", appName)
                .form("title", title)
                .cookie(jobLoginService.getCookie())
                .execute();
        Object code = JSONUtil.parse(response.body()).getByPath("code");
        return code.equals(HttpStatus.HTTP_OK);
    }
}
